/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2011 All Rights Reserved.
 */
package com.liwei.nio.mina;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

/**
*
* @author lidian
* @version $Id: MyProtocalServer.java, v 0.1 2011-1-27 上午10:12:51 lidian Exp $
*/
public class MyProtocalServer {
    private static final int PORT   = 2500;
    static Logger            logger = Logger.getLogger(MyProtocalServer.class);

    public static void main(String[] args) throws IOException {
        PropertyConfigurator.configure("conf\\log4j.properties");
        IoAcceptor acceptor = new NioSocketAcceptor();
        Log4jFilter lf = new Log4jFilter(logger);
        acceptor.getFilterChain().addLast("logger", lf);

        acceptor.getFilterChain().addLast("codec",
            new ProtocolCodecFilter(new MyProtocalCodecFactory(Charset.forName("GBK"))));
        acceptor.getSessionConfig().setReadBufferSize(1024);
        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
        acceptor.setHandler(new MyHandler());
        acceptor.bind(new InetSocketAddress(PORT));
        System.out.println("start server ...");
    }
}

class MyHandler extends IoHandlerAdapter {
    static Logger logger = Logger.getLogger(MyHandler.class);

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        cause.printStackTrace();
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        MyProtocalPack pack = (MyProtocalPack) message;
        logger.debug("Rec:" + pack);
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        logger.debug("IDLE " + session.getIdleCount(status));
    }
}
